<link rel="stylesheet" href="/stylesheets/admin.css">
<link rel="stylesheet" href="/stylesheets/style.css">
<link href="/multiselect/css/multi-select.css" media="screen" rel="stylesheet" type="text/css">

<style>
    .ms-container {
        /*width: 305px;*/
    }
    .app-icon {
        max-height:34px;
        margin: 0px 20px;
    }
</style>
<div class="row">
    <div class="col-xs-12">
        <div class="container-header">
            <p class="container-title"><%= platform %> 应用管理</p>
        </div>
        <div class="setting-div">
            <div class="setting-header-div">
                <div>
                    <button id="create-btn" class="create-btn btn btn-default">添加应用</button>

                    <% if (type === 1 && user.role && user.role.permissions.managerA) {  %>
                    <a href="/app?platform=android" class="list-header-btn btn btn-default">切换到 Android</a>
                    <% } else if (type === 2 && user.role && user.role.permissions.managerI) { %>
                    <a href="/app?platform=ios" class="list-header-btn btn btn-default">切换到 iOS</a>
                    <% } %>

                </div>
                <hr>
            </div>
            <div>
                <table class="table table-striped">
                    <thead>
                    <tr>
                        <th>图标</th>
                        <th>名称</th>
                        <th>标识</th>
                        <th>工程名</th>
                        <th>版本</th>
                        <th>配置</th>
                        <!--<th>仓库地址</th>-->
                        <th>Git分支</th>
                        <th>Git路径</th>
                        <th>Git用户</th>
                        <% if (type === 1) {%>
                        <th>打包证书</th>
                        <% } %>
                        <th>通知机器人</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="list-body">
                    </tbody>
                </table>
            </div>
            <div class="setting-footer-div">

            </div>
        </div>
        <div style="height: 40px"></div>
    </div>
</div>
<!-- 模态框（Modal） -->
<div class="modal fade" value="<%= isNew %>" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">添加应用</h4>
            </div>
            <div class="modal-body">
                <form id="edit-form" class="form-horizontal" role="form">
                    <div class="form-group">
                        <label for="icon" class="col-sm-3 control-label">图标</label>
                        <div class="col-sm-6">
                            <input type="file" name="icon" class="form-control" accept=".png,.jpg,.jpeg" num="1" id="icon">
                        </div>
                        <div class="col-sm-3">
                            <img class="app-icon" id="previewImage" src="" alt="">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="name" class="col-sm-3 control-label">名称</label>
                        <div class="col-sm-9">
                            <input type="text" name="name" class="form-control" id="name" placeholder="请输入应用名称">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="bundleId" class="col-sm-3 control-label">标识</label>
                        <div class="col-sm-9">
                            <input type="text" name="bundleId" class="form-control" id="bundleId" placeholder="请输入应用标识">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="project" class="col-sm-3 control-label">工程名</label>
                        <div class="col-sm-9">
                            <input type="text" name="project" class="form-control" id="project" placeholder="请输入应用工程名">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="version" class="col-sm-3 control-label">版本</label>
                        <div class="col-sm-9">
                            <input type="text" name="version" class="form-control" id="version" placeholder="请输入当前版本">
                        </div>
                    </div>

                    <% if (type === 1) {%>
                    <div class="form-group">
                        <label for="configuration" class="col-sm-3 control-label">配置</label>
                        <div class="col-sm-9">
                            <input type="text" name="configuration" class="form-control" id="configuration" placeholder="请输入配置，默认为Release">
                        </div>
                    </div>
                    <% } else { %>
                    <div class="form-group">
                        <label for="configuration" class="col-sm-3 control-label">配置</label>
                        <div class="col-sm-9">
                            <input type="text" name="configuration" class="form-control" id="configuration" placeholder="请输入配置">
                        </div>
                    </div>
                    <% } %>

                    <div class="form-group">
                        <label for="token" class="col-sm-3 control-label">Git地址</label>
                        <div class="col-sm-9">
                            <input type="text" name="url" class="form-control" id="url" placeholder="请输入Git地址">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="branch" class="col-sm-3 control-label">Git分支</label>
                        <div class="col-sm-9">
                            <input type="text" name="branch" class="form-control" id="branch" placeholder="请输入Git分支">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="gitPath" class="col-sm-3 control-label">Git路径</label>
                        <div class="col-sm-9">
                            <input type="text" name="gitPath" class="form-control" id="gitPath" placeholder="请输入Git下工程路径，可选">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="gituser" class="col-sm-3 control-label">Git用户</label>
                        <div class="col-sm-9">
                            <select class="form-control" name="gituser" id="gituser">
                                <% if (gitusers && gitusers.length) { %>
                                <option value="">不使用</option>
                                <% gitusers.forEach(function(gituser){ %>
                                <option value=<%= gituser._id%>><%= gituser.name%></option>
                                <% }) %>
                                <% } else { %>
                                <option value="">不使用</option>
                                <% } %>
                            </select>
                        </div>
                    </div>

                    <% if (type === 1) {%>
                    <div class="form-group">
                        <label for="sign" class="col-sm-3 control-label">签名证书</label>
                        <div class="col-sm-9">
                            <input type="text" name="sign" class="form-control" id="sign" placeholder="请输入签名证书（iOS必填）">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="teamid" class="col-sm-3 control-label">TEAM ID</label>
                        <div class="col-sm-9">
                            <input type="text" name="teamid" class="form-control" id="teamid" placeholder="请输入TEAM ID">
                        </div>
                    </div>
                    <% } %>
                    <div class="form-group">
                        <label for="status" class="col-sm-3 control-label">当前状态</label>
                        <div class="col-sm-9">
                            <select class="form-control" name="status" id="status">
                                <option value="0">正常</option>
                                <option value="-1">禁止打包</option>
                                <option value="1">正在打包</option>
                            </select>
                            <!--<input type="text" name="status" class="form-control" id="status" placeholder="请输入签名证书（iOS必填）">-->
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="robots" class="col-sm-3 control-label">通知机器人</label>
                        <div class="col-sm-9">
                            <select multiple="multiple" class="form-control" id="robots" style="width: 320px">
                                <% if (robots && robots.length > 0) { %>
                                <% robots.forEach(function(robot){ %>
                                <option value=<%= robot._id%>><%= robot.name%></option>
                                <% }) %>
                                <% } else { %>
                                <option value="" disabled>无可选机器人</option>
                                <% } %>
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" id="submit-btn" class="btn btn-primary">提交</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>
<link rel="stylesheet" href="/stylesheets/jquery-confirm.min-3.2.3.css">
<script src="/multiselect/js/jquery.multi-select.js" type="text/javascript"></script>
<!--<script src="/javascripts/date-extension.js" type="text/javascript"></script>-->
<script src="/javascripts/version-extension.js" type="text/javascript"></script>
<script src="/javascripts/jquery-confirm.min-3.1.1.js"></script>
<script language="JavaScript">

    var robotList = [];

    $('#robots').multiSelect({
        afterSelect: function(value){
            robotList.push(value[0]);
        },
        afterDeselect: function(value){
            var index = robotList.indexOf(value[0]);
            robotList.splice(index,1);
        }
    });

    var editId = null;

    function delClick(node) {
        $.confirm({
            title: '确定要删除该APP？',
            content: '删除后将无法恢复',
            animationBounce: 1.5,
            animation: 'rotateXR',
            closeAnimation: 'rotateYR',
            buttons: {
                ok: {
                    text: "确定",
                    btnClass: 'btn-success',
                    keys: ['enter'],
                    action: function(){
                        var tdNode = node.parentNode.parentNode;
                        var id = tdNode.id;
                        delAction(id)
                    }
                },
                cancel: {
                    text: "取消",
                    action:function(){
                    }
                }
            }
        });
    }

    function delAction(id) {
        $.post('/app/del',{id:id},function (data) {
            if (data.code === 0) {
                showSuccess('已删除');
                loadAppList();
            } else {
                showError(data.message);
            }
        });
    }

    $("#create-btn").click(function () {
        $('#myModalLabel').text('添加应用');
        robotList = [];
        document.getElementById('previewImage').src = '';
        $('#name').val('');
        $('#code').val('');
        $('#project').val('');
        $('#url').val('');
        $('#gitPath').val('');
        $('#version').val('');
        $('#branch').val('');
        $('#sign').val('');
        $('#teamid').val('');
        $("#gituser option").each(function(i,n){
            if($(n).text()==='不使用')
            {
                $(n).attr("selected",true);
            } else  {
                $(n).attr("selected",false);
            }
        })

        $('#configuration').val('');
        $('#robots').multiSelect('deselect_all');
        $("#status option").each(function(i,n){
            if($(n).text()==='正常')
            {
                $(n).attr("selected",true);
            } else  {
                $(n).attr("selected",false);
            }
        })
        $('#myModal').modal('show');
        editId = null;
    })

    function editClick(node) {
        $('#myModalLabel').text('添加应用');
        var tdNode = node.parentNode.parentNode;
        var id = tdNode.id;
        document.getElementById('previewImage').src = $('#icon-' + id + ' img')[0].src;
        $('#name').val(document.getElementById('name-' + id).innerText);
        $('#bundleId').val(document.getElementById('bundleId-' + id).innerText);
        $('#project').val(document.getElementById('project-' + id).innerText);
        $('#branch').val(document.getElementById('branch-' + id).innerText);
        $('#gitPath').val(document.getElementById('gitPath-' + id).innerText);
        $('#configuration').val(document.getElementById('config-' + id).innerText);
        <% if (type === 1) { %>
        $('#sign').val(document.getElementById('sign-' + id).innerText);
        $('#teamid').val(document.getElementById('team-' + id).innerText);
        <% } %>
        $('#status').val(document.getElementById('status-' + id).innerText);
        $('#version').val(document.getElementById('version-' + id).innerText);

        var gituserInfo = document.getElementById('gituser-' + id).innerText;

//        var role = $('#role').val();
        $("#gituser option").each(function(i,n){
            if($(n).text()===gituserInfo)
            {
                $(n).attr("selected",true);
            } else  {
                $(n).attr("selected",false);
            }
        })

        var url = $("#name-" + id + ' a').attr('value');
        $('#url').val(url);

        var robotIdList = [];
        $("#robots-"+id+" li").each(function (i,n) {
            var value = $(n).attr("value");
            robotIdList.push(value);
        })
        robotList = [];
        $('#robots').multiSelect('select',robotIdList);

        var statusInfo = document.getElementById('status-' + id).innerText;
//        var role = $('#role').val();
        $("#status option").each(function(i,n){
            if($(n).text()===statusInfo)
            {
                $(n).attr("selected",true);
            } else  {
                $(n).attr("selected",false);
            }
        })

        $('#myModal').modal('show');

        editId = id;
    }

    $("#submit-btn").click(function () {

        var formdata = new FormData(document.getElementById('edit-form'));

        formdata.append('robots',JSON.stringify(robotList));
        if (editId) {
            formdata.append('id',editId);

            $.ajax({
                url:'/app/edit',
                type : 'post',
                data:formdata,
                processData : false,
                contentType : false,
                success : function (data) {
                    if (data.code === 0) {
                        $('#myModal').modal('hide');
                        showSuccess('已更新应用 ' + name);
                        loadAppList();
                    } else  {
                        showError(data.message);
                    }
                }
            })
        } else  {

            $.ajax({
                url:'/app/add',
                type : 'post',
                data:formdata,
                processData : false,
                contentType : false,
                success : function (data) {
                    if (data.code === 0) {
                        $('#myModal').modal('hide');
                        showSuccess('已添加应用 ' + name);
                        loadAppList();
                    } else  {
                        showError(data.message);
                    }
                }
            })
        }
    })
    $(function () {
        loadAppList();

        document.getElementById('icon').onchange = function(evt) {
            // 如果浏览器不支持FileReader，则不处理
            if (!window.FileReader) return;
            var files = evt.target.files;
            for (var i = 0, f; f = files[i]; i++) {
                if (!f.type.match('image.*')) {
                    continue;
                }
                var reader = new FileReader();
                reader.onload = (function(theFile) {
                    return function(e) {
                        // img 元素
                        document.getElementById('previewImage').src = e.target.result;
                    };
                })(f);
                reader.readAsDataURL(f);
            }
        }

        var isNew = $('#myModal').attr('value');
        if (parseInt(isNew) !== 0) {
            $("#create-btn").click();
        }
    })

    function loadAppList() {
        $.post("/app/list",function (data) {
            if (data.code == 0) {
                var parent = document.getElementById('list-body');
                for (var i = parent.children.length - 1; i >= 0; i--) {
                    parent.removeChild(parent.children[i]);
                }
                for (var i = 0 ; i < data.data.length ; i++) {
                    var app = data.data[i];
                    var appNode = document.createElement('tr');
                    var id = app._id;

                    appNode.id = id;
                    var nameNode = document.createElement('td');
                    nameNode.id = 'name-' + id;
                    nameNode.innerHTML = "<a target='_blank' href='" + app.gitlab + "' value='" + app.gitlab + "'>" + app.name + "</a>";
//                    nameNode.innerText = app.name;
//                    var urlNode = document.createElement('td');
//                    urlNode.id = 'url-' + id;
//                    urlNode.innerHTML = "<a target='_blank' href='" + component.url + "' value='" + component.url + "'>点击查看</a>";

                    var versionNode = document.createElement('td');
                    versionNode.id = 'version-' + id;
                    versionNode.innerText = app.version;

                    var configNode = document.createElement('td');
                    configNode.id = 'config-' + id;
                    configNode.innerText = app.configuration || 'CI';

                    var gitpathNode = document.createElement('td');
                    gitpathNode.id = 'gitPath-' + id;
                    gitpathNode.innerText = app.gitPath;

                    var bundleIdNode = document.createElement('td');
                    bundleIdNode.id = 'bundleId-' + id;
                    bundleIdNode.innerText = app.bundleId;

                    var iconNode = document.createElement('td');
                    iconNode.innerHTML = '<img style="width: 34px" src="' + app.iconUrl + '"></img>';
                    iconNode.id = 'icon-' + id;

//                    var gitUrlNode = document.createElement('td');
//                    gitUrlNode.innerText = app.gitlab;

                    var branchNode = document.createElement('td');
                    branchNode.id = 'branch-' + id;
                    branchNode.innerText = app.branch;

                    var projectNode = document.createElement('td');
                    projectNode.id = 'project-' + id;
                    projectNode.innerText = app.projectName;

                    var signNode = document.createElement('td');
                    signNode.id = 'sign-' + id;
                    signNode.innerText = app.sign;

                    var teamNode = document.createElement('td');
                    teamNode.id = 'team-' + id;
                    teamNode.hidden = 'true';
                    teamNode.innerText = app.teamId;

                    var statusNode = document.createElement('p');
                    statusNode.id = 'status-' + id;
                    statusNode.hidden = 'true';
                    statusNode.innerText = app.status;

                    var gituserNode = document.createElement('td');
                    gituserNode.innerText = app.gitUser ? app.gitUser.name : '无';
                    gituserNode.id = 'gituser-' + id;

                    var robotsNode = document.createElement('td');
//                    robotsNode.innerText = component.robots;
                    var robotHTML = '<ul style="list-style-type:none;padding-left: 0px">';
                    app.robots.forEach(function (robot) {
                        var add = '<li value="' + robot._id + '">' + robot.name + '</li>';
                        robotHTML += add;
                    })
                    robotHTML += '</ul>'
                    robotsNode.id = 'robots-' + id;
                    robotsNode.innerHTML = robotHTML;

                    var  editNode = document.createElement('td');
                    if (app.status !== 1) {
                        editNode.innerHTML = "<a class='btn btn-default' onclick='editClick(this)'>编辑</a>&nbsp;&nbsp;<a class='btn btn-default' onclick='delClick(this)'>删除</a>";
                    } else  {
                        editNode.innerHTML = "<a class='btn btn-default' disabled=''>打包中</a>";
                    }
                    editNode.appendChild(statusNode);

                    appNode.appendChild(iconNode);
                    appNode.appendChild(nameNode);
                    appNode.appendChild(bundleIdNode);
                    appNode.appendChild(projectNode);
                    appNode.appendChild(versionNode);
                    appNode.appendChild(configNode);
                    appNode.appendChild(branchNode);
                    appNode.appendChild(gitpathNode);
                    appNode.appendChild(gituserNode);
                    <% if (type === 1) {%>
                    appNode.appendChild(signNode);
                    <% } %>
                    appNode.appendChild(robotsNode);
                    appNode.appendChild(editNode);
                    appNode.appendChild(teamNode);
                    parent.appendChild(appNode);
                }

            } else  {

            }
        })
    }
</script>